<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2025/3/6} {14:02} 
 */

namespace wanghua\general_utility_tools_php\tool;

/**
 * ai生成音频
 * Class AudioAiTool
 * @package app\api\logic
 */
class AudioAiTool
{
    private $ai_config = [];
    public function __construct($ai_config)
    {
        $this->ai_config = $ai_config;
    }
    /**
     * desc：阶跃AI生成音频
     *
     *
     * author：wh
     * $audio_file_name 生成的音频文件名（推荐使用用户唯一id），默认为当前时间戳
     *
     * doc: https://platform.stepfun.com/docs/llm/audio
     *
     * 使用示例：
    $txt = input('txt','收款到账12.03元！支付后有惊喜哦！~');
    $phone = input('phone');
    $ai_config = config('step_fun_ai_config');
    $ai_config['model'] = 'step-tts-mini';
    $ai_config['voice'] = 'jilingshaonv';//'yuanqinansheng';
    $ai_config['speed'] = 1.1;
    $ai_config['volume'] = 1.5;//可选值为 0.1~2.0 ，代表着将音量缩小至 10% ~ 增大至 200%（两倍音量）

    //音频文件名称
    $audio_file_name = "/partner/payment_audio/".$phone;
    $res = (new AudioAiTool($ai_config))->stepfunBuildAudioMp3($txt,$audio_file_name);
    if($res['code'] != 200){
        return Tools::set_fail('生成音频失败');
    }

    $url = request()->domain().'/'.$res['data']['rel'];
    echo "<a target='_blank' href='{$url}'>点击</a>";die;
    //return Tools::set_ok('ok',['url'=>$url]);
     */
    public function stepfunBuildAudioMp3(string $txt,$audio_file_name = ''){
        $url = $this->ai_config['base_url']?:'https://api.stepfun.com/v1/audio/speech';
        $apiKey = $this->ai_config['APIKey'];//'KJS9PN05iwG9peJpPHW2y8uBHDLTEu6B6e1xIsA4QSxhVEn2DV7kMQeoWD4H2ecA';
        unset($this->ai_config['base_url']);
        unset($this->ai_config['APIKey']);
        //speed 参数，可选值为 0.5-2 ，代表着将语速降速为之前的一半 ~ 提速至两倍
        $data = array_merge($this->ai_config,[
            'model' => $this->ai_config['model']?:'step-tts-mini',
            'input' => $txt?:'智能阶跃，十倍每一个人的可能',
            'voice' => $this->ai_config['voice']?:'cixingnansheng',
            'speed' => $this->ai_config['speed']?:1,
        ]);
        $headers = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey,
        ];
        $dir_arr = $this->createMp3Dir($audio_file_name);
        if(empty($dir_arr)){
            return Tools::set_fail('生成音频失败');
        }
        $real_path = $dir_arr[0];//物理路径
        $rel_url = $dir_arr[1];//相对路径

        $result = $this->curlPost($url, $data, $headers, false);
        // 将响应内容保存为 MP3 文件
        if ($result !== false) {
            // 尝试写入文件
            if (file_put_contents($real_path, $result)) {
                //echo "音频文件已保存为：{$filename} <a target='_blank' href='/{$rel}'>访问</a>\n";
                return Tools::set_ok('ok',['rel'=>$rel_url]);
            } else {
                //echo "写入文件 {$filename} 失败\n";
                Tools::log_to_write_txt(['error'=>"写入文件失败: {$real_path} "]);
                return Tools::set_fail('生成音频失败');
            }
        } else {
            //echo "请求失败\n";
            Tools::log_to_write_txt(['error'=>"请求失败: {$url} "]);
            return Tools::set_fail('生成音频失败');
        }
    }

    /**
     * desc：创建目录
     * author：wh
     * @param string $audio_file_name 文件名不能有"空格"等特殊符号
     */
    private function createMp3Dir($audio_file_name='')
    {
        $time = $audio_file_name?:(date('YmdHis'));
        $root_path = Tools::get_root_path();
        $rel = "audio/{$time}.mp3";
        $real_path = $root_path . "public/" . $rel;
        $dir = dirname($real_path);

        // 检查并创建目录
        if (!file_exists($dir)) {
            if (!mkdir($dir, 0777, true)) {
                //echo "目录 {$dir} 创建成功\n";
            //} else {
                //echo "目录 {$dir} 创建失败\n";
                Tools::log_to_write_txt(['error'=>"目录创建失败: {$dir} "]);
                return [];
            }
        }
        return [$real_path, $rel];
    }

    protected function curlPost($url, $data, $headers, $verifySSL = true)
    {
        $jsonData = json_encode($data);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        if (!$verifySSL) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
            return false;
        }

        curl_close($ch);

        return $response;
    }
}